﻿using RayD.Core;
using RayD.Repository;
using RayD.Repository.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;

namespace RayD.App
{
    public abstract class BaseApp
    {
        #region 构造函数注入
        public IRepository BaseRepository;
        public BaseApp(IRepository repository)
        {
            this.BaseRepository = repository;
        }
        #endregion

        #region 数据验证
        /// <summary>
        /// 验证字段值是否存在
        /// </summary>
        /// <param name="id">实体主键</param>
        /// <param name="field">字段名</param>
        /// <param name="value">字段值</param>
        /// <returns></returns>
        public virtual bool ValidateExist<T>(string id, string field, string value) where T : class, new()
        {
            var expression = LinqExtensions.True<T>();
            if (!string.IsNullOrEmpty(id))
            {
                expression = expression.And(t => getIdValue(t).ToString() != id);
            }
            return this.BaseRepository.IQueryable(expression).Exist(field, value);
        }
        #endregion
        private object getIdValue<T>(T entity) where T : class, new()
        {
            PropertyInfo keyProp = typeof(T)
                .GetProperties()
                .Where(prop => prop.IsDefined(typeof(KeyAttribute), true))
                ?.First();
            return keyProp.GetValue(entity);
        }
    }
}
